import router from '@/router'
import store from '@/store'
import nProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { asyncRoutes } from '@/router'
// 路由前置守卫
const whiteList = ['/login', '/404'] // 白名单
router.beforeEach(async(to, from, next) => {
  nProgress.start()
  if (store.getters.token) {
    if (to.path === '/login') {
      next('/')
      nProgress.done()
    } else {
      // 先获取个人信息，再进入系统首页
      if (!store.getters.userId) {
        await store.dispatch('user/getInfo')
        // console.log(store.state.user.userInfo.roles.menus)
        const routes = store.state.user.userInfo.roles.menus
        console.log(asyncRoutes)
        // 筛选用户的页面访问权
        const filterRoutes = asyncRoutes.filter(item => routes.includes(item.children[0].name))
        store.commit('user/addRoute', filterRoutes)
        // console.log(filterRoutes)
        // 为路由添加新的规则
        router.addRoutes([...filterRoutes, { path: '*', redirect: '/404', hidden: true }])
        next(to.path)// addRoutes的问题，addRoutes新增的规则路由实例创建的这些规则并不在routes
      }
      next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      nProgress.done()
    }
  }
})
router.afterEach((to, from) => {
  nProgress.done()
})
